<template>
  <el-dialog
    v-model="visible"
    title="JSA详情"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="jsaData" class="jsa-detail">
      <!-- 基本信息 -->
      <el-card class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        
        <el-descriptions :column="3" border>
          <el-descriptions-item label="JSA编号">{{ jsaData.jsaNumber }}</el-descriptions-item>
          <el-descriptions-item label="分析单位">{{ jsaData.analysisUnit }}</el-descriptions-item>
          <el-descriptions-item label="任务描述">{{ jsaData.jobDescription }}</el-descriptions-item>
          <el-descriptions-item label="工作位置">{{ jsaData.workPosition }}</el-descriptions-item>
          <el-descriptions-item label="工作时间段">
            <span v-if="jsaData.workDateDuration">
              {{ jsaData.workDateDuration[0] }} 至 {{ jsaData.workDateDuration[1] }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="工作负责人">
            {{ getPersonName(jsaData.personInCharge) }}
          </el-descriptions-item>
          <el-descriptions-item label="权威认可">
            {{ getPersonName(jsaData.areaApproval) }}
          </el-descriptions-item>
          <el-descriptions-item label="案例分享" :span="2">{{ jsaData.caseSharing }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- JSA分析表 -->
      <el-card class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><List /></el-icon>
            <span>JSA分析表</span>
          </div>
        </template>
        
        <JSATemplateTable 
          v-if="analysisTemplateData" 
          :template="analysisTemplateData" 
        />
        <el-empty v-else description="暂无分析数据" />
      </el-card>
      
      <!-- 措施落实责任人 -->
      <el-card v-if="stepResponsibilities.length > 0" class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><User /></el-icon>
            <span>措施落实责任人</span>
          </div>
        </template>
        
        <div class="responsibility-list">
          <div 
            v-for="(item, index) in stepResponsibilities" 
            :key="index"
            class="responsibility-item"
          >
            <div class="step-info">
              <div class="step-number">{{ index + 1 }}</div>
              <div class="step-name">{{ item.stepName }}</div>
            </div>
            <div class="responsible-persons">
              <el-tag
                v-for="personId in item.responsiblePersons || []"
                :key="personId"
                style="margin: 2px 4px 2px 0"
              >
                {{ getPersonName(personId) }}
              </el-tag>
              <span v-if="!item.responsiblePersons || item.responsiblePersons.length === 0" class="no-responsible">
                未指定责任人
              </span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 分析人员 -->
      <el-card v-if="jsaData.analyzers && jsaData.analyzers.length > 0" class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><UserFilled /></el-icon>
            <span>分析人员</span>
          </div>
        </template>
        
        <div class="analyzer-list">
          <el-tag
            v-for="analyzerId in jsaData.analyzers"
            :key="analyzerId"
            style="margin: 4px 8px 4px 0"
          >
            {{ getPersonName(analyzerId) }}
          </el-tag>
        </div>
      </el-card>
      
      <!-- 确认要求 -->
      <el-card class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><Check /></el-icon>
            <span>确认要求</span>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="需要确认的人员">
            <el-tag
              v-for="confirmer in jsaData.confirmers || []"
              :key="confirmer"
              style="margin: 2px 4px 2px 0"
            >
              {{ getConfirmerLabel(confirmer) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="确认截止时间">{{ jsaData.confirmDeadline }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 确认状态 -->
      <el-card class="detail-section">
        <template #header>
          <div class="section-title">
            <el-icon><Check /></el-icon>
            <span>确认状态</span>
          </div>
        </template>
        
        <div class="confirmation-status">
          <div 
            v-for="(item, index) in confirmationStatus" 
            :key="index"
            class="confirmation-item"
          >
            <div class="person-info">
              <div class="person-name">{{ item.personName }}</div>
              <div class="person-role">{{ item.role }}</div>
            </div>
            <div class="confirmation-info">
              <el-tag 
                :type="item.status === 'confirmed' ? 'success' : item.status === 'pending' ? 'warning' : 'info'"
                :icon="item.status === 'confirmed' ? 'Check' : item.status === 'pending' ? 'Clock' : 'Close'"
              >
                {{ getStatusLabel(item.status) }}
              </el-tag>
              <div class="confirmation-time">
                {{ item.confirmTime || '未确认' }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Document, List, User, UserFilled, Check, Clock, Close } from '@element-plus/icons-vue'
import JSATemplateTable from './JSATemplateTable.vue'
import type { JSATemplate } from '@/types'

interface JSAFormData {
  jsaNumber: string
  analysisUnit: string
  jobDescription: string
  workPosition: string
  workDateDuration: [string, string] | null
  personInCharge: string
  personsAnalyzedJob: string[]
  areaApproval: string
  caseSharing: string
  analyzers: string[]
  confirmers: string[]
  confirmDeadline: string
  // JSA分析数据
  analysisData?: {
    name: string
    jobType: string
    workSteps: Array<{
      stepName: string
      responsiblePersons?: string[]
    }>
    hazards: Array<{
      hazardName: string
    }>
    controlMeasures: Array<{
      measureName: string
    }>
    workStepHazards: Array<{
      workStepSequence: number
      hazardName: string
    }>
    hazardControls: Array<{
      hazardName: string
      controlMeasureName: string
    }>
  }
}

interface Props {
  modelValue: boolean
  jsaData?: JSAFormData
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 人员选项数据
const personnelOptions = [
  { id: '1', name: '张三', department: '安全部' },
  { id: '2', name: '李四', department: '工程部' },
  { id: '3', name: '王五', department: '技术部' },
  { id: '4', name: '赵六', department: '质量部' },
  { id: '5', name: '钱七', department: '安全部' },
  { id: '6', name: '孙八', department: '工程部' },
  { id: '7', name: '周九', department: '技术部' },
  { id: '8', name: '吴十', department: '质量部' }
]

// 获取人员名称
const getPersonName = (personId: string) => {
  const person = personnelOptions.find(p => p.id === personId)
  return person ? `${person.name} (${person.department})` : personId
}

// 获取确认人员标签
const getConfirmerLabel = (confirmer: string) => {
  const labels: Record<string, string> = {
    analyzers: '分析人员',
    responsible_persons: '措施责任人',
    safety_officer: '安全员',
    supervisor: '主管'
  }
  return labels[confirmer] || confirmer
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    confirmed: '已确认',
    pending: '待确认',
    rejected: '已拒绝'
  }
  return labels[status] || '未知状态'
}

// 确认状态数据
const confirmationStatus = computed(() => {
  if (!props.jsaData) return []
  
  const statusData = [
    // 分析人员确认状态
    ...(props.jsaData.analyzers || []).map((personId, index) => ({
      personName: getPersonName(personId),
      role: '分析人员',
      status: index % 3 === 0 ? 'confirmed' : index % 3 === 1 ? 'pending' : 'rejected',
      confirmTime: index % 3 === 0 ? '2024-01-15 14:30:00' : index % 3 === 1 ? null : '2024-01-15 15:20:00'
    })),
    // 措施责任人确认状态
    ...(props.jsaData.confirmers || []).includes('responsible_persons') ? [
      { personName: '张三 (安全部)', role: '措施责任人', status: 'confirmed', confirmTime: '2024-01-15 16:00:00' },
      { personName: '李四 (工程部)', role: '措施责任人', status: 'pending', confirmTime: null }
    ] : [],
    // 安全员确认状态
    ...(props.jsaData.confirmers || []).includes('safety_officer') ? [
      { personName: '王五 (安全部)', role: '安全员', status: 'confirmed', confirmTime: '2024-01-15 17:30:00' }
    ] : [],
    // 主管确认状态
    ...(props.jsaData.confirmers || []).includes('supervisor') ? [
      { personName: '赵六 (质量部)', role: '主管', status: 'pending', confirmTime: null }
    ] : []
  ]
  
  return statusData
})

// 分析模板数据，用于预览模式显示
const analysisTemplateData = computed<JSATemplate | undefined>(() => {
  if (!props.jsaData?.analysisData) return undefined
  
  const analysisData = props.jsaData.analysisData
  
  // 将JSATemplateForm转换为JSATemplate格式用于预览
  return {
    id: 0,
    name: analysisData.name || 'JSA分析表',
    jobType: analysisData.jobType || '',
    workSteps: analysisData.workSteps.map((step, index) => ({
      id: index + 1,
      stepName: step.stepName,
      sequence: index + 1
    })),
    hazards: analysisData.hazards.map((hazard, index) => ({
      id: index + 1,
      hazardName: hazard.hazardName
    })),
    controlMeasures: analysisData.controlMeasures.map((measure, index) => ({
      id: index + 1,
      measureName: measure.measureName
    })),
    workStepHazards: analysisData.workStepHazards.map((relation, index) => ({
      id: index + 1,
      workStepId: relation.workStepSequence,
      hazardId: analysisData.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
      workStep: {
        id: relation.workStepSequence,
        stepName: analysisData.workSteps[relation.workStepSequence - 1]?.stepName || '',
        sequence: relation.workStepSequence
      },
      hazard: {
        id: analysisData.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
        hazardName: relation.hazardName
      }
    })),
    hazardControls: analysisData.hazardControls.map((relation, index) => ({
      id: index + 1,
      hazardId: analysisData.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
      controlMeasureId: analysisData.controlMeasures.findIndex(m => m.measureName === relation.controlMeasureName) + 1,
      hazard: {
        id: analysisData.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
        hazardName: relation.hazardName
      },
      controlMeasure: {
        id: analysisData.controlMeasures.findIndex(m => m.measureName === relation.controlMeasureName) + 1,
        measureName: relation.controlMeasureName
      }
    })),
    isActive: true,
    createTime: new Date().toLocaleString('zh-CN'),
    updateTime: new Date().toLocaleString('zh-CN'),
    creator: '当前用户'
  }
})

// 步骤责任人数据
const stepResponsibilities = computed(() => {
  if (!props.jsaData?.analysisData?.workSteps) return []
  
  return props.jsaData.analysisData.workSteps.map(step => ({
    stepName: step.stepName,
    responsiblePersons: step.responsiblePersons || []
  }))
})

const handleClose = () => {
  visible.value = false
}
</script>

<style lang="scss" scoped>
.jsa-detail {
  .detail-section {
    margin-bottom: 20px;
    
    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 500;
    }
  }
  
  .responsibility-list {
    .responsibility-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .step-info {
        display: flex;
        align-items: center;
        min-width: 200px;
        margin-right: 20px;
        
        .step-number {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          font-size: 12px;
          font-weight: 600;
          margin-right: 12px;
        }
        
        .step-name {
          font-weight: 500;
          color: #303133;
          flex: 1;
        }
      }
      
      .responsible-persons {
        flex: 1;
        
        .no-responsible {
          color: #909399;
          font-style: italic;
        }
      }
    }
  }
  
  .analyzer-list {
    min-height: 40px;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background: #f8f9fa;
  }
  
  .confirmation-status {
    .confirmation-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafbfc;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .person-info {
        .person-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .person-role {
          font-size: 12px;
          color: #606266;
        }
      }
      
      .confirmation-info {
        text-align: right;
        
        .confirmation-time {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
